<template> 
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float:right"
          type="primary"
          @click="handleSearchList()"
          size="small">
          查询搜索
        </el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="输入搜索：">
            <el-input v-model="listQuery.keyword" class="input-width" placeholder="员工工号" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button size="mini" class="btn-add" @click="handleAdd()" style="margin-left: 20px">添加</el-button>
    </el-card>
      <div class="table-container">
        <!-- 展示所有员工列表 -->
        <div v-if="!foundEmployee">
          <el-table ref="adminTable"
                    :data="employeeList"
                    style="width: 100%;"
                    v-loading="listLoading" border>
            <el-table-column label="编号" width="100" align="center">
              <template slot-scope="scope">{{scope.row.id}}</template>
            </el-table-column>
            <el-table-column label="姓名" align="center">
              <template slot-scope="scope">{{scope.row.employeeName}}</template>
            </el-table-column>
            <el-table-column label="性别" align="center">
              <template slot-scope="scope">{{scope.row.employeeSex}}</template>
            </el-table-column>
            <el-table-column label="工号 " align="center">
              <template slot-scope="scope">{{scope.row.employeeId}}</template>
            </el-table-column>
            <el-table-column label="手机号 " align="center">
              <template slot-scope="scope">{{scope.row.phone}}</template>
            </el-table-column>
            <el-table-column label="身份证号 " align="center">
              <template slot-scope="scope">{{scope.row.birthday}}</template>
            </el-table-column>
            <el-table-column label="工作地点 " align="center">
              <template slot-scope="scope">{{scope.row.workAddress}}</template>
            </el-table-column>
            <el-table-column label="入职时间 " align="center">
              <template slot-scope="scope">{{scope.row.workDay}}</template>
            </el-table-column>
            <el-table-column label="离职时间 " align="center">
              <template slot-scope="scope">{{scope.row.leaveDay}}</template>
            </el-table-column>
            <el-table-column label="备注" width="100" align="center">
              <template slot-scope="scope">{{scope.row.more}}</template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="text"
                           @click="handleUpdate(scope.$index, scope.row)">编辑
                </el-button>
                <el-button size="mini"
                           type="text"
                           @click="handleDelete(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 展示找到的员工信息 -->
        <div v-else>
          <h3>找到的员工信息:</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="编号">{{ foundEmployee.id }}</el-descriptions-item>
            <el-descriptions-item label="姓名">{{ foundEmployee.employeeName }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ foundEmployee.employeeSex }}</el-descriptions-item>
            <el-descriptions-item label="工号">{{ foundEmployee.employeeId }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ foundEmployee.phone }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ foundEmployee.birthday }}</el-descriptions-item>
            <el-descriptions-item label="部门">{{ foundEmployee.employeeDepartment }}</el-descriptions-item>
            <el-descriptions-item label="工作地点">{{ foundEmployee.workAddress }}</el-descriptions-item>
            <el-descriptions-item label="入职时间">{{ foundEmployee.workDay }}</el-descriptions-item>
            <el-descriptions-item label="离职时间">{{ foundEmployee.leaveDay }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ foundEmployee.more }}</el-descriptions-item>
          </el-descriptions>
          <el-button @click="clearFoundEmployee">返回列表</el-button>

        </div>
      </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :title="isEdit?'编辑用户':'添加用户'"
      :visible.sync="dialogVisible"
      width="40%">
      <el-form :model="admin"
               ref="adminForm"
               label-width="150px" size="small">
        <el-form-item label="姓名：">
          <el-input v-model="admin.employeeName" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="性别：">
          <el-input v-model="admin.employeeSex" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="工号：">
          <el-input v-model="admin.employeeId" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="手机号：">
          <el-input v-model="admin.phone" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="身份证号：">
          <el-input v-model="admin.birthday" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="部门：">
          <el-input v-model="admin.employeeDepartment" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="工作地点：">
          <el-input v-model="admin.workAddress" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="入职时间：">
          <el-input v-model="admin.workDay" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="离职时间：">
          <el-input v-model="admin.leaveDay" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="admin.more"  type="password" style="width: 250px"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allocDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleAllocDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {fetchList,createAdmin,updateAdmin,updateStatus,deleteAdmin,getRoleByAdmin,allocRole} from '@/api/login';
import {fetchAllRoleList} from '@/api/role';
import {formatDate} from '@/utils/date';

const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  keyword: null
};
const defaultAdmin = {
  id: null,
  username: null,
  password: null,
  nickName: null,
  email: null,
  note: null,
  status: 1
};
export default {
  name: 'adminList',
  data() {
    return {
      listQuery: Object.assign({}, defaultListQuery),
      employeeList: [], // 存储所有员工列表的数据
      list: null,
      total: null,
      listLoading: false,
      dialogVisible: false,
      admin: Object.assign({}, defaultAdmin),
      isEdit: false,
      allocDialogVisible: false,
      allocRoleIds:[],
      allRoleList:[],
      allocAdminId:null,
      foundEmployee: null, // 存储通过 ID 查找到的单个员工信息
    }
  },
  created() {
    this.getEmployeeMessage();
  },
  filters: {
    formatDateTime(time) {
      if (time == null || time === '') {
        return 'N/A';
      }
      let date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    }
  },
  methods: {
    // 获取数据
    getEmployeeMessage(){
      fetch("http://localhost:8080/employee/list", {
        method: "POST",
        headers: {
          'Content-Type': 'application/json'
        },
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          console.log('Success:', data);
          this.employeeList = data.data;
        })
        .catch(error => {
          console.error('Error:', error);
          alert('网络请求失败，请稍后再试');
        })
    },
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getEmployeeMessageByEmployeeId()
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    handleAdd() {
      this.dialogVisible = true;
      this.isEdit = false;
      // this.admin = Object.assign({},defaultAdmin);
    },
    // 删除数据
    handleDelete(index, row) {
      this.$confirm('是否要删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        fetch("http://localhost:8080/employee/delete", {
          method: "POST",
          headers: {
            'Content-Type': 'application/json'
          },
          body: row.employeeId,
        })
          .then(response => {
            if (!response.ok) {
              throw new Error('Network response was not ok');
            }
            return response.json();
          })
          .then(data => {
            console.log('Success:', data);
            this.getEmployeeMessage();
          })
          .catch(error => {
            console.error('Error:', error);
            alert('网络请求失败，请稍后再试');
          })
      });
    },
    handleUpdate(index, row) {
      this.dialogVisible = true;
      this.isEdit = true;
      this.admin = Object.assign({},row);
    },
    handleDialogConfirm() {
      this.$confirm('是否要确认?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.isEdit) {
          const employeeMessage = this.admin // 假设 admin 对象符合 EmployeeMessage 结构

          fetch("http://localhost:8080/employee/change", {
            method: "POST",
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(employeeMessage) // 直接发送 admin 对象作为请求体
          })
            .then(response => {
              if (!response.ok) {
                throw new Error(`Network response was not ok, status: ${response.status}`);
              }
              return response.json();
            })
            .then(data => {
              // 假设服务器返回的状态码在 data.code 或 data.state 中
              if (data.state === 200 || data.code === 200) {
                this.$message({
                  message: '修改成功！',
                  type: 'success'
                });
                this.dialogVisible = false;
                this.getEmployeeMessage(); // 刷新列表
              } else {
                // 如果服务器返回了非成功的状态码，给出相应提示
                this.$message({
                  message: `修改失败：${data.message || '未知错误'}`,
                  type: 'error'
                });
              }
            })
            .catch(error => {
              console.error('Error:', error);
              this.$message({
                message: '网络请求失败，请稍后再试',
                type: 'error'
              });
            });
        } else {
          fetch("http://localhost:8080/employee/insert", {
            method: "POST",
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(this.admin)
          })
            .then(response => {
              if (!response.ok) {
                throw new Error('Network response was not ok');
              }
              return response.json();
            })
            .then(data => {
              if(data.state === 200){
                this.$message({
                  message: '添加成功！',
                  type: 'success'
                });
                this.dialogVisible =false;
                this.getEmployeeMessage();
              }
            })
            .catch(error => {
              console.error('Error:', error);
              alert('网络请求失败，请稍后再试');
            })
        }
      })
    },
    handleAllocDialogConfirm(){
      this.$confirm('是否要确认?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = new URLSearchParams();
        params.append("adminId", this.allocAdminId);
        params.append("roleIds", this.allocRoleIds);
        allocRole(params).then(response => {
          this.$message({
            message: '分配成功！',
            type: 'success'
          });
          this.allocDialogVisible = false;
        })
      })
    },
    getEmployeeMessageByEmployeeId(){
      const employeeId = this.listQuery.keyword
      fetch("http://localhost:8080/employee/find", {
        method: "POST",
        headers: {
          'Content-Type': 'application/json'
        },
        body: employeeId,
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          console.log('Success:', data);
          this.foundEmployee = data.data;
          // this.getEmployeeMessage();
        })
        .catch(error => {
          console.error('Error:', error);
          alert('网络请求失败，请稍后再试');
        })
    },
    clearFoundEmployee(){
      this.foundEmployee = null;
    },
  }
}
</script>
<style></style>


